package com.bodystm.web;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bodystm.config.PublicSetting;
import com.bodystm.server.GatherServer;
import com.bodystm.server.WebSocketManager;
import com.bodystm.service.AlarmRecordService;
import com.bodystm.service.BedService;
import com.bodystm.service.PatientBedService;
import com.bodystm.service.PatientService;
import com.bodystm.service.TemperatureService;
import com.bodystm.system.SystemSetting;
import com.bodystm.system.SystemSettingService;

/**
 * 鍒濆鍖栧苟璧峰姩閲囬泦鏈嶅姟绋嬪簭
 * 
 * @author ggeagle
 *
 */
@SuppressWarnings("serial")
public class GatherServerServlet extends HttpServlet {
	/**
	 * 鏃ュ織璁板綍鍣�
	 */
	private Logger logger = LoggerFactory.getLogger(GatherServer.class);
	/**
	 * 閲囬泦鏈嶅姟
	 */
	private GatherServer gatherServer;
	/**
	 * 鏈嶅姟鐨勭鍙ｅ彿
	 */
	private int port = 10000;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doPost(req, resp);
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String portValue = config.getInitParameter("serverPort");
		if (StringUtils.isNotBlank(portValue)) {
			port = Integer.parseInt(portValue);
		}
		WebApplicationContext context = WebApplicationContextUtils
				.getRequiredWebApplicationContext(config.getServletContext());
		TemperatureService temperatureService = (TemperatureService) context
				.getBean("temperatureService");
		PatientService patientService=(PatientService) context
				.getBean("patientService");
		PatientBedService patientBedUserService=(PatientBedService)context
				.getBean("patientBedService");
		AlarmRecordService alarmRecordService=(AlarmRecordService)context
				.getBean("alarmRecordService");
		BedService bedService=(BedService)context
				.getBean("bedService");

		//初始化系统参数：
		org.springframework.core.io.Resource resource = new ClassPathResource("/applicationContext.properties");//
        Properties props;
		try {
			props = PropertiesLoaderUtils.loadProperties(resource);
			String s=props.getProperty("num4expirehours");
	        SystemSetting.NUM4EXPIREHOURS=Integer.parseInt(s);
	        logger.info("初始化系统参数（过期时间）成功！"+s);
	        String ifMeasureScreen=props.getProperty("ifMeasureScreen").toUpperCase();
	        PublicSetting.ifMeasureScreen=ifMeasureScreen.equals("TRUE")?true:false;
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			logger.info("没有获取系统参数设置！");
		}
		
		//初始化系统参数：是否在采集数据时取平均值
		SystemSettingService systemSettingService=(SystemSettingService)context
				.getBean("systemSettingService");
		SystemSetting systemSetting = systemSettingService.getSystemSetting();
		if (systemSetting!=null) {
			SystemSetting.ifGetAvgInDataGather4Temp=systemSetting.isIfGetAvgInDataGather()==1?true:false;
			logger.info("初始化系统参数（是否取平均值）成功！"+systemSetting.isIfGetAvgInDataGather()+":::"+SystemSetting.ifGetAvgInDataGather4Temp);
		}else{
			logger.info("没有获取系统参数设置！");
			SystemSetting.ifGetAvgInDataGather4Temp=true;
		}
		try {
			this.gatherServer = new GatherServer(port);
			this.gatherServer.setTemperatureService(temperatureService);
			this.gatherServer.setPatientService(patientService);
			this.gatherServer.setPatientBedUserService(patientBedUserService);
			this.gatherServer.setBedService(bedService);
			this.gatherServer.setAlarmRecordService(alarmRecordService);
			this.gatherServer.setServletConfig(config);
			new Thread(this.gatherServer).start();
			Class.forName("com.bodystm.server.WebSocketManager");
			WebSocketManager webSocketManager=new WebSocketManager();
			new Thread(webSocketManager).start();
		} catch (IOException | ClassNotFoundException e) {
			logger.error("起动采集任务失败：", e);
		}
	}

	@Override
	public void destroy() {
		super.destroy();
		this.gatherServer = null;
	}
}